package com.mb.common.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mb.app.constants.Constants;
import com.mb.common.service.NotifysService;
import com.mb.common.utils.Base64Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * redis 消息订阅处理器
 * @author
 * @create 2018-05-22 下午5:38
 **/
@Service
@Slf4j
public class RedisReceiver {

    @Autowired
    private NotifysService notifyService;

    /**
     * 处理订阅消息
     * @param message
     */
    public void receiveMessage(String message) {
        log.info("RedisReceiver message :"+message);

        try {
            String redisMsg = Base64Utils.decode(message);
            log.info("redisMsg :"+redisMsg);

            redisMsg = redisMsg.replaceAll("\\\\","");
            JSONObject topicJson = JSONObject.parseObject(redisMsg);
            if(topicJson != null){
                String topic = topicJson.getString("topic");
                log.info("constants::"+Constants.RedisTopic.ORDER_MSG.getCode().equals(topic));
                if(Constants.RedisTopic.ORDER_MSG.getCode().equals(topic)){
                    JSONObject msgJson = topicJson.getJSONObject("msg");
                    String orderId = msgJson.getString("orderId");
                    String msg = msgJson.getString("msg");
                    Map<String,Object> msgMap = new HashMap<String, Object>();
                    msgMap.put("orderId",orderId);
                    msgMap.put("msg",msg);
                    notifyService.sendNotify(msgMap);
                }
            }
        } catch (Exception e) {
            log.error("receiveMessage Exception",e);
        }
    }

}
